package de.bastian.hinterleitner.tools;

import java.util.List;

import android.content.Context;

public class Unit {

	private final double valueInDollars;
	private final String sign;
	private final String name;

	public Unit(String sign, String name, double valueInDollars) {
		this.sign = sign;
		this.name = name;
		this.valueInDollars = valueInDollars;
	}

	public double inDollar(double value) {
		return value * valueInDollars;
	}
	
	public double convert(double value, Unit targetUnit){
		if(targetUnit.valueInDollars == valueInDollars){
			return value;
		}
		
		double euros = inDollar(value);
		double targetAmount = euros / targetUnit.valueInDollars;
		
		return targetAmount;
	}

	public String getSign() {
		return sign;
	}

	public String getName() {
		return name;
	}

	public static boolean exists(String unit, Context c) {

		
		if (Constants.getUnitNames(c).contains(unit)) {
			return true;
		}

		if (Constants.getUnits(c).contains(unit)) {
			return true;
		}

		return false;
	}

	public static Unit get(String unit, Context c) {
		if (!exists(unit, c)) {
			return new Unit(unit, unit, 1);
		}
		
		int index = -1;
		String u = unit;
		String name = unit;
		double exchange = 1.0;
		
		List<String> names = Constants.getUnitNames(c);
		List<String> units = Constants.getUnits(c);
		List<String> exchanges = Constants.getUnitExchange(c);
		
		index = names.indexOf(unit);
		if(index == -1){
			index = units.indexOf(unit);
			name = names.get(index);
		}
		
		try{
			exchange = Double.parseDouble(exchanges.get(index));
		}catch(NumberFormatException e){
			exchange = 1.0;
		}
		
		return new Unit(u, name, exchange);
	}

}
